"""
演示Python的闭包特性
"""

# 简单闭包
# def outer(logo):
#     def inner(msg):
#         print(f"<{logo}>{msg}<{logo}>")
#     return inner
#
# fn = outer("黑马程序员")
# fn("大家好")
# fn("你好呀")
#
# fn2 = outer("传智播客")
# fn2("大家好呀")

# 使用nonlocal关键字修改外部函数的值
# def outer(num):
#     def inner(num2):
#         nonlocal num
#         num += num2
#         print(num)
#     return inner
#
# fn = outer(10)
# fn(10)
# fn(10)

# 使用闭包实现ATM案例
def outer(initial_amount = 0):
    def atm(money, deposit=True):
        nonlocal initial_amount
        if deposit:
            initial_amount += money
            print(f"存款金额为：{money}")
        else:
            initial_amount -= money
            print(f"取款金额为：{money}")
        print(f"剩余金额为：{initial_amount}")
    return atm

fn = outer()
fn(100)
fn(200, True)
fn(100, False)